#include <stdio.h>
#include <e_file.h>
#include <string.h>
#include <signal.h>
#include "tbf.h"

#define BUFFSIZE 10
#define CPS      10 //速率
#define BURST	 (20*(CPS)) //上限值

/*
	比如1钟积攒10个令牌， 1min并不是积攒600个, 而是200个
	令牌：
	token 
	cps 
	burst 
 */
static int token = 0;
int mycopy (int rfd, int wfd);

int main (int argc, char ** argv)
{
	int fd1, fd2;
	fd2 = 1;
	int cnt = 0;
	char buf[BUFFSIZE] = {0};
	if (argc < 2) {
		return -1;
	}
	//打开argv[1]文件
	fd1 = open (argv[1], O_RDONLY);
	if (-1 == fd1) {
		perror ("open ()");
	}
	//打开argv[2]文件
	if (argc >= 3) {
		fd2 = open (argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0666);
		if (-1 == fd2) {
			perror ("open ()");
		}
	}
	mycopy (fd1, fd2);
	close (fd1);
	close (fd2);
	return 0;
}

int mycopy (int rfd, int wfd)
{
	int cnt = 0;
	char buf[BUFFSIZE] = {0};
	int td; 
	int n;
	//初始化令牌桶
	td = tbf_init (CPS, TBF_MAX);
	if (td < 0) {
		fprintf (stderr, "tbf_init () failed!\n");
		return -1;
	}
	while (1) {
		//控制速率 --》令牌桶模型
		n = fetch_token (td, CPS);
		memset (buf, 0, BUFFSIZE);
		//sleep (1);
		cnt = read (rfd, buf, n);
		if (-1 == cnt) {
			fprintf (stderr, "read() failed!\n");
			goto ERROR;
		}
		if (0 == cnt) {
			break;
		}
		write (wfd, buf, cnt);
	}
	tbf_destroy_all ();
	return 0;
ERROR:
	close (rfd);
	close (wfd);
	return -1;
}






